package mylog

import (
	"context"
	"fmt"
	"io"
	"log/slog"
)

type CustomHandler struct {
	Writer io.Writer
}

func (h *CustomHandler) Handle(ctx context.Context, r slog.Record) error {
	timeStr := r.Time.Format("2006-01-02 15:04:05")
	level := r.Level.String()
	msg := r.Message

	// 自定义格式
	logLine := fmt.Sprintf("[%s] %s: %s", timeStr, level, msg)

	// 添加属性
	r.Attrs(func(attr slog.Attr) bool {
		logLine += fmt.Sprintf(" %s=%v", attr.Key, attr.Value)
		return true
	})

	logLine += "\n"
	_, err := h.Writer.Write([]byte(logLine))
	return err
}

func (h *CustomHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	// 简化实现 - 返回自身
	return h
}

func (h *CustomHandler) WithGroup(name string) slog.Handler {
	// 简化实现 - 返回自身
	return h
}

func (h *CustomHandler) Enabled(ctx context.Context, level slog.Level) bool {
	return level >= slog.LevelInfo
}
